package com.igeek.yygh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igeek.yygh.listener.MyAnalysisEventListener;
import com.igeek.yygh.mapper.DictMapper;
import com.igeek.yygh.model.cmn.Dict;
import com.igeek.yygh.service.DictService;
import com.igeek.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author Guzhenghui
 * @since 2024/8/19
 */
@CacheConfig(cacheNames = "dict" , keyGenerator = "keyGenerator")
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

//    @Transactional(readOnly = true)
    @Cacheable
    @Override
    public List<Dict> findAllData(Long id) {
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id!=null,Dict::getParentId,id);
        List<Dict> dicts = this.baseMapper.selectList(wrapper);
        dicts = dicts.stream().map(dict -> {
            //是否包含子节点  true代表包含子节点，false代表不包含子节点
            boolean flag = this.hasChildren(dict.getId());
            dict.setHasChildren(flag);
            return dict;
        }).collect(Collectors.toList());
        return dicts;
    }



    //判断当前项是否有子节点
    private boolean hasChildren(Long id) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id!=null ,Dict::getParentId , id);
        Long count = this.baseMapper.selectCount(queryWrapper);
        return count>0?true:false;
    }

    @Override
    public void exportData(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        //封装数据
        List<Dict> dicts = this.baseMapper.selectList(null);
        List<DictEeVo> dictEeVos = dicts.stream().map(dict -> {
            //Dict -> DictEeVo
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            return dictEeVo;
        }).collect(Collectors.toList());

        //EasyExcel 写dictEeVos数据
        EasyExcel.write(response.getOutputStream() , DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);
    }

    @CacheEvict(allEntries = true , beforeInvocation = true)
    @Override
    public void importData(MultipartFile multipartFile) throws IOException {
        if(multipartFile!=null){
            EasyExcel.read(multipartFile.getInputStream() , DictEeVo.class , new MyAnalysisEventListener(this.baseMapper))
                    .sheet("数据字典").doRead();
        }
    }
}
